﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Tycho.Parser.Peg {
    public class CompositeTerm : Term {
        public string Name;
        public Dictionary<string, ITerm> SubTerms;

        public CompositeTerm (string name, SourceInformation sourceInformation) : base (sourceInformation) {
            Name = name;
            SubTerms = new Dictionary<string, ITerm> ();
        }

        public void Add (string name, ITerm term, bool isMultiple) {
            if (!isMultiple) {
                if (!SubTerms.ContainsKey (name)) {
                    SubTerms.Add (name, term);
                } else {
                    throw new NamedRuleAlreadySetException (name);
                }
            } else {
                AddMuliple (name, term);
            }
        }

        private void AddMuliple (string name, ITerm term) {
            ITerm foundTerm;
            ListTerm listTerm;
            if (!SubTerms.TryGetValue (name, out foundTerm)) {
                listTerm = new ListTerm (SourceInformation);
                SubTerms.Add (name, listTerm);
            } else {
                if (foundTerm is ListTerm) {
                    listTerm = foundTerm as ListTerm;
                } else {
                    throw new NamedListRuleAlreadySetException (name);
                }
            }

            listTerm.Terms.Add (term);
        }

        public override string ToString()
        {
            string subTerms = String.Join (", ", SubTerms.Select (st => String.Format ("{0}: {1}", st.Key, st.Value)).ToArray ());
            return Name + " {" + subTerms + "}";
        }
    }
}